/*
 * @Date: 2023-01-11 12:20:16
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-23 16:52:32
 * @FilePath: \A19\backend\src\api\Login\ApiRegist.ts
 */
/*
 * @Date: 2023-01-11 12:20:16
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-04 16:23:19
 * @FilePath: \A19\backend\src\api\Login\ApiRegist.ts
 */
import { Global } from './../../Global/index';
import { Folder } from './../../utils/Folder';
import { ApiCall } from "tsrpc";
import { ReqRegist, ResRegist } from "../../shared/protocols/Login/PtlRegist";
import upload from "../../utils/upload";

export default async function (call: ApiCall<ReqRegist, ResRegist>) {
    // TODO
    const { portrait, role, name, gender, email, password } = call.req
    const user = await Global.collection('users').findOne({
        email
    })
    if (user) {
        console.log("existed");
        call.error('该邮箱已被注册过')
        return
    }
    console.log("asdfasdf");
    
    if(portrait){
        //portrait
        const index = portrait.fileType.indexOf('/')
        const typeCate = portrait.fileType.slice(0, index)
        const type = portrait.fileType.slice(index + 1)
        // console.log(type);
        const fileInfo = {
            folder: Folder.portraits,
            typeCate,
            type
        }
        console.log(fileInfo);

        try {
            const ret = await upload(fileInfo, portrait.fileDate)//   /portraits/image1673518207632.png
            const user = {
                name,
                password,
                role,
                email,
                gender,
                portrait: ret
            }
            const res = await Global.collection('users').insertOne({
                ...user,
                school: '',
                number: ''
            })
            console.log(res);
    
            call.succ({})
        } catch (error) {
            call.error('error');
        }
    }
    else{
        const user = {
            name,
            password,
            role,
            email,
            gender,
            portrait: '/User.ico'
        }
        const res = await Global.collection('users').insertOne({
            ...user,
            school: '',
            number: ''
        })
        console.log(res);

        call.succ({})
    }
}